import wx from '../../../subwe/bridge';
import WXPage from "../../../subwe/page";
import { Index } from '../../../apis/index.js';
import util from "../../../utils/util";
const app = getApp();
const API = new Index();
let computeOrderCostTime = null;
WXPage({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    loginInfo: {}, // 登录信息
    contentHeight: 0,
    listdata:[],  //数据
    pageNum: 1,
    pageSize: 10,
    showMoreVisable: false,
    statusMap: {1: '等待下单', 2: '服务中', 3: '已撤销', 4: '交易失败', 5: '已归还', 6: '支付超时', 7: '待守约', 8: '已恢复', 10: '已删除', 11: '退款'},
    showAd: 1,
    imageUrl: `${app.globalData.imageUrl}`
  },
  onLoad: async function (options) {
    this.setData({
      loginInfo: wx.getStorageSync('login_key'),
      contentHeight: app.globalData.windowH - this.data.CustomBar - 130,
      showAd: wx.getStorageSync("showAd")
    });
    if (!this.data.loginInfo) {
      // 登录
      await API.getLoginToken().then(res => {
        this.setData({
          loginInfo: res.result
        });
        wx.setStorageSync("login_key", res.result);
      });
    }
    await this.getOrderList(this.data.pageNum);
  },
  // 计算订单时长与费用
  computeOrderCost(list) {
    let clearIntervalOff = true
    for (let item of list) {
      let t = '0分钟'
      let money = 0
      if (item.state === 2) {
        let timeLen = parseInt((new Date().getTime() - new Date(item.beginAt.replace(/\-/g, '/')).getTime()) / 1000)
        timeLen = timeLen > 0 ? timeLen : 0
        let {h, m, s} = util.secondToTime(timeLen > 0 ? timeLen : 0)
        t = `${h}时${m}分`

        if (item.feeMode === 1) {
          money = item.priceTypeInfo.payIntervalPrice / (item.priceTypeInfo.payInterval * 60) * timeLen
          if (money > item.priceTypeInfo.maxPayPrice) money = item.priceTypeInfo.maxPayPrice
          money = (money / 100).toFixed(2)
        } else money = (item.priceTypeInfo.useDuration / 100).toFixed(2)

        clearIntervalOff = false
      }

      else if (item.state === 5) {
        let timeLen = parseInt((new Date(item.endAt.replace(/\-/g, '/')).getTime() - new Date(item.beginAt.replace(/\-/g, '/')).getTime()) / 1000)
        timeLen = timeLen > 0 ? timeLen : 0
        let {h, m, s} = util.secondToTime(timeLen > 0 ? timeLen : 0)
        t = `${h}时${m}分`
      }

      item.useTime = t
      if (money) item.settlementMoneyStr = money
      else if (!item.settlementMoneyStr || item.state !== 5) item.settlementMoneyStr = '0.00'
    }

    clearInterval(computeOrderCostTime)
    if (!clearIntervalOff) computeOrderCostTime = setInterval(ev => this.computeOrderCost(list), 1000)

    this.setData({listdata: list})
  },
  getOrderList: function(pageNum) {
    wx.showLoading({ title: '加载中', mask: true })
    var param = {
      pageNo: pageNum,
      pageSize: this.data.pageSize,
    }
    if (param.pageNo === 1) this.data.listdata = []
    API.getOrderList(param).then(res => {
      wx.hideLoading()
      var listData = this.data.listdata.concat(res.result.data)
      var showMore = false
      if (res.result.totalCount > listData.length) {
        showMore = true
      }
      this.computeOrderCost(listData)
      this.setData({
        listdata: listData,
        showMoreVisable: showMore
      })
    })
  },
  // 显示更多
  showMore: function () {
    var pageNum = this.data.pageNum += 1;
    console.log(pageNum);
    this.getOrderList(pageNum);
  },
  // openDetail: function() {
  //   wx.navigateTo({
  //     url: '../orderdetail/orderdetail',
  //   })
  // }
  // 结束订单，结束使用
  closeOrder: function (e) {
    var loginInfo = wx.getStorageSync('login_key');
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否结束订单',
      success(res) {
        if (res.confirm) {
          var param = {
            "deviceSn": e.currentTarget.dataset.devicesn,
            "productId": e.currentTarget.dataset.productid,
            "openid": loginInfo.openid,
            "tradeNo": e.currentTarget.dataset.trade
          };
          API.closeOrder(param).then(res => {
            // wx.showToast({
            //   title: '已归还',
            // })
            wx.redirectTo({
              url: '/pages/orderDetail/orderDetail?settMoney=' + res.result.settMoney + '&useTime=' + res.result.useTime + '&returnMoney=' + res.result.returnMoney + '&productId=' + that.data.orderInfo.productId + '&deviceSn=' + e.currentTarget.dataset.devicesn
            });
            // wx.redirectTo({
            //   url: '/pages/orderDetail/orderDetail?settMoney=' + res.result.settMoney + '&useTime=' + res.result.useTime + '&returnMoney=' + res.result.returnMoney,
            // })
          });
        } else if (res.cancel) {}
      }
    });
    that.onShow();
  },
  onShow: function () {
    // this.getOrderList(this.data.pageNum)
  },
  onHide: function () {
    clearInterval(computeOrderCostTime);
  },
  onUnload: function () {
    clearInterval(computeOrderCostTime);
  },
  getHistory: function () {
    wx.navigateTo({
      url: '/pages/mine/history/history'
    });
  },
  // 订单异常
  toRepairs(ev) {
    // ev.mark = ev.target.dataset

    // let {
    //   deviceSn,
    //   tradeNo
    // } = ev.mark;
    let {
      deviceSn,
      tradeNo
    } = ev.mark;
    wx.navigateTo({
      url: `/pages/report/report?deviceSn=${deviceSn}&tradeNo=${tradeNo}`
    });
  },
  // 跳转详情
  toDeatail(ev) {
    // return console.log(ev)
    // ev.mark = ev.target.dataset
    wx.navigateTo({
      url: '/pages/mine/orderdetail/orderdetail?tradeNo=' + ev.mark.tradeNo
    });
  }
});

// pages/order/history/history.js
// Page({
//
//   /**
//    * 页面的初始数据
//    */
//   data: {
//
//   },
//
//   /**
//    * 生命周期函数--监听页面加载
//    */
//   onLoad: function (options) {
//
//   },
//   // 订单异常
//   toRepairs() {
//     wx.navigateTo({
//       url: '/pages/report/report',
//     })
//   },
//   // 跳转详情
//   toDeatail() {
//     wx.navigateTo({
//       url: '/pages/mine/orderdetail/orderdetail',
//     })
//   },
// })
